#! /usr/bin/env python
#coding:utf-8

# alert check daemon
import sys
import os
import re
import json
import redis
import time
import django
import urllib
import urllib2
import requests
import traceback
import pickle
from datetime import datetime, date, timedelta
#from alert_daemon import client_send
#from apscheduler.schedulers.blocking import BlockingScheduler

reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "longquan.settings")
django.setup()
from deadnotice.models import *
from django.core.mail import send_mail

def send_sacrifice_email(message):
    #test
    #send_mail('Subject here', 'Here is the message.', 'admin@163.com', ['redfox_qu@163.com'])
    managers = Manager.objects.all()
    mail_list = [m.email for m in managers]
    print message
    #print mail_list
    #send_mail('防火预警', message, 'redfox_qu@163.com', ['redfox_qu@163.com'])
    send_mail('防火预警', message, 'redfox_qu@163.com', mail_list)

def sacrifice_day_check():
    check_day = date.today()
    prog = re.compile(".*_d$")
    deadman_list = Deadman.objects.all().order_by('dead_date')
    fire_day0 = []
    fire_day1 = []
    for deadman_obj in deadman_list:
        #print deadman_obj
        deadman_date_map = deadman_obj.GetSacrificeDay()
        deadman_day_list = [ld for ld in deadman_date_map.keys() if prog.search(ld)]
        for sf_day in deadman_day_list:
            dt = deadman_date_map[sf_day] - check_day
            #print deadman_obj, deadman_date_map[sf_day], check_day, dt.days
            if dt.days == 0:
                ld_name = re.match("(.*_)d", sf_day).group(1) + "ld"
                sf_day_name = Deadman.GetSacrificeExplain().get(sf_day)
                fire_notice = "【%s村】%s，死于%s，%s：阳历：%s，阴历：%s，亲属：%s，联系电话：%s" % \
                    (deadman_obj.village, deadman_obj.deadman_name, deadman_obj.dead_date, sf_day_name, \
                    deadman_date_map[sf_day], deadman_date_map[ld_name], deadman_obj.kin_name, deadman_obj.phone)
                fire_day0.append(fire_notice)
            if dt.days == 1:
                ld_name = re.match("(.*_)d", sf_day).group(1) + "ld"
                sf_day_name = Deadman.GetSacrificeExplain().get(sf_day)
                fire_notice = "【%s村】%s，死于%s，%s：阳历：%s，阴历：%s，亲属：%s，联系电话：%s" % \
                    (deadman_obj.village, deadman_obj.deadman_name, deadman_obj.dead_date, sf_day_name, \
                    deadman_date_map[sf_day], deadman_date_map[ld_name], deadman_obj.kin_name, deadman_obj.phone)
                fire_day1.append(fire_notice)
    message = '今日预警：\n%s\n\n' % ('\n'.join(fire_day0))
    send_sacrifice_email(message)
    message = '明日预警：\n%s\n\n' % ('\n'.join(fire_day1))
    send_sacrifice_email(message)


if __name__ == '__main__':
    #acard_alert_clear(r)
    #attend_data_cache_clear(r)

    #while True:
    dt = datetime.now()
    '''
    if dt.hour < 8 or dt.hour >= 21:
        print dt, 'sleeping...'
        time.sleep(60)
        continue
    '''
    try:
        print ''
        print dt
        sacrifice_day_check()
        #attend_turnout(dt)
    except Exception as e:
        print "error:", str(e)
        traceback.print_exc()
    #time.sleep(60*60*24)

